const express = require("express");
const db = require("../../config/dbserver.js");

const router = express.Router();

// 获取广告初始项
router.get("/ad-init", async (req, res) => {
  const sql = `
    SELECT * FROM ad_c WHERE id = 1
  `;
  const data = await db.dbQuery(sql);
  if (data?.[0]) {
    const vd = data[0];
    res.send({
      code: 200,
      data: {
        initial: vd.init_ad,
        repeat: vd.cad_type,
        infinity: vd.infinity_type,
        infinityDelay: vd.infinity_delay
      },
      message: "success"
    });
  } else {
    res.send({
      code: 500,
      data: null,
      message: "读取失败"
    });
  }
});

// 设置广告初始项和反复控制项
router.post("/ad-set", async (req, res) => {
  const { initial, repeat, infinity, infinityDelay } = req.body;
  // initial = ?
  // cad_type = ?
  const params = {
    init_ad: initial,
    cad_type: repeat,
    infinity_type: infinity,
    infinity_delay: infinityDelay
  };
  const sql = `
    UPDATE ad_c 
    SET ${Object.keys(params)
      .filter((key) => params[key])
      .map((key) => `${key} = ?`)
      .join(", ")} 
    WHERE id = 1
  `;
  const otherParams = [Number(infinityDelay) || 1000].filter((v) => v);
  const result = await db.dbQuery(sql, [
    ...[initial, repeat, infinity].filter((v) => v).map((v) => v.join(",")),
    ...otherParams
  ]);
  if (!result) {
    return res.send({
      code: 500,
      data: {},
      message: "update fail"
    });
  }
  res.send({
    code: 200,
    data: {},
    message: "success"
  });
});

// 获取数据
router.get("/data", async (req, res) => {
  // 数据区取数据
  const sql = `
    SELECT * FROM ad_c
  `;
  const data = await db.dbQuery(sql);

  if (data?.[0]) {
    const d = data[0];
    const dd = {
      id: d.id,
      filter: JSON.parse(d.filter),
      showAD: d.show_ad === 1
      // cad_type: d.cad_type
    };

    res.send({
      code: 200,
      data: dd,
      message: "success"
    });
  } else {
    res.send({
      code: 500,
      data: null,
      message: "读取失败"
    });
  }
});

// 保存数据
router.post("/save-city", async (req, res) => {
  const data = req.body;
  try {
    const sql = `
      UPDATE ad_c SET filter = ? WHERE id = 1
    `;
    const result = await db.dbQuery(sql, [JSON.stringify(data)]);
    if (!result) throw "update fail";
    res.send({
      code: 200,
      data: data,
      message: "success"
    });
  } catch (error) {
    res.send({
      code: 500,
      data: {},
      message: error
    });
  }
});

router.get("/set-show", async (req, res) => {
  try {
    const { show } = req.query;
    const sql = `
      UPDATE ad_c SET show_ad = ? WHERE id = 1
    `;
    const result = await db.dbQuery(sql, [show == "true" ? 1 : 0]);
    if (!result) throw "update fail";
    res.send({
      code: 200,
      data: {},
      message: "success"
    });
  } catch (error) {
    res.send({
      code: 500,
      data: String(error),
      message: "写入失败"
    });
  }
});

module.exports = router;
